package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class HealthRecordDetailTestController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private LoginService loginService;

    // /healthRecordDetailTest/getUser 钩子函数，获取当前用户信息，并返回
    @RequestMapping("/healthRecordDetailTest/getUser")
    public Result getUser(HttpServletResponse resp, HttpServletRequest req){
        try {
            Cookie[] cookies = req.getCookies();
            String userCookieName = null;

            for (Cookie cookie : cookies) {
                //System.out.println(cookie.getName());
                if ("login_member_telephone".equals(cookie.getName())){
                    userCookieName = cookie.getValue();
                    break;
                }
            }
            if(userCookieName == null){
                //System.out.println("还没有登录");
                return new Result(false,"您还没有登录，请登录后重试");
            }
            //System.out.println(userCookieName);
            String userJson = jedisPool.getResource().get(userCookieName);
            if(userJson == null){
                return new Result(false,"您还没有登录，请登录后重试");
            }
            //System.out.println(userJson);
            int index1 = userJson.indexOf(',');
            int index2 = userJson.indexOf(':');
            String s1 = userJson.substring(0,index1);
            String s2 = s1.substring(index2+1);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(s2)));
            //System.out.println(date);
            String s3 = userJson.substring(index1);
            String s4 = s1.substring(0,index2+1);
            String json = s4+date+s3;

            Gson gson = new Gson();
            Member member= gson.fromJson(json, Member.class);
            System.out.println(member);
            return new Result(true,"查询用户信息成功",member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询信息失败，请稍后再试");
        }
    }

    // 查询该用户名对应的数据

    // /healthRecordDetailTest/update
    @RequestMapping("/healthRecordDetailTest/update")
    public Result update(@RequestBody Member member){
        return loginService.update(member);
    }
    @RequestMapping("/healthRecordDetailTest/send4updatephoneNumber")
    public Result send4updatephoneNumber(@RequestBody Member member,String validateCode){
        Member member2 = loginService.getById(member.getId());
        try {
            String validateCodeInJedisPool = jedisPool.getResource().get(member2.getPhoneNumber()+ RedisMessageConstant.SENDTYPE_UPDATE);
            if(validateCodeInJedisPool == null || validateCode == null || !validateCode.equals(validateCodeInJedisPool)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR,member2);
            }
            return loginService.update(member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.VALIDATECODE_ERROR,member2);
        }
    }

    //////////////////////////////////////////////////////////////

    // /1menus/get1menus

    @RequestMapping("/1menus/get1menus")
    public Result get1menus(HttpServletResponse resp, HttpServletRequest req){
        try {
            Cookie[] cookies = req.getCookies();
            String userCookieName = null;

            for (Cookie cookie : cookies) {
                //System.out.println(cookie.getName());
                if ("login_member_telephone".equals(cookie.getName())) {
                    userCookieName = cookie.getValue();
                    break;
                }
            }
            if (userCookieName == null) {
                //System.out.println("还没有登录");
                return new Result(false, "您还没有登录，请登录后重试");
            }
            //System.out.println(userCookieName);
            String userJson = jedisPool.getResource().get(userCookieName);
            if (userJson == null) {
                return new Result(false, "您还没有登录，请登录后重试");
            }
            //System.out.println(userJson);
            int index1 = userJson.indexOf(',');
            int index2 = userJson.indexOf(':');
            String s1 = userJson.substring(0, index1);
            String s2 = s1.substring(index2 + 1);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(s2)));
            //System.out.println(date);
            String s3 = userJson.substring(index1);
            String s4 = s1.substring(0, index2 + 1);
            String json = s4 + date + s3;

            Gson gson = new Gson();
            Member member = gson.fromJson(json, Member.class);
            return loginService.getByMemberId(member.getId());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询信息失败，请稍后再试,或者是联系管理人员");
        }
    }

    // /1menus/get1menusByTime
    @RequestMapping("/1menus/get1menusByTime")
    public Result get1menusByTime(String startDate,String endDate,HttpServletResponse resp, HttpServletRequest req){
        try {
            Cookie[] cookies = req.getCookies();
            String userCookieName = null;

            for (Cookie cookie : cookies) {
                //System.out.println(cookie.getName());
                if ("login_member_telephone".equals(cookie.getName())) {
                    userCookieName = cookie.getValue();
                    break;
                }
            }
            if (userCookieName == null) {
                //System.out.println("还没有登录");
                return new Result(false, "您还没有登录，请登录后重试");
            }
            //System.out.println(userCookieName);
            String userJson = jedisPool.getResource().get(userCookieName);
            if (userJson == null) {
                return new Result(false, "您还没有登录，请登录后重试");
            }
            //System.out.println(userJson);
            int index1 = userJson.indexOf(',');
            int index2 = userJson.indexOf(':');
            String s1 = userJson.substring(0, index1);
            String s2 = s1.substring(index2 + 1);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(s2)));
            //System.out.println(date);
            String s3 = userJson.substring(index1);
            String s4 = s1.substring(0, index2 + 1);
            String json = s4 + date + s3;

            Gson gson = new Gson();
            Member member = gson.fromJson(json, Member.class);
            return loginService.getByMemberIdAndStartDateAndendDate(member.getId(),startDate,endDate);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询信息失败，请稍后再试,或者是联系管理人员");
        }
    }

    // /2menus/findBymemberIdAndsetmealId
    @RequestMapping("/2menus/findBymemberIdAndsetmealId")
    public Result findBymemberIdAndsetmealId(Integer memberId,Integer setmealId){
        return loginService.getByMemberIdAndsetmealId(memberId,setmealId);
    }

    @RequestMapping("/healthRecordDetailTest/logon.do")
    public Result login(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("login_member_telephone".equals(name)){
                    return new Result(true,"欢迎回家");
                }
            }
        }return new Result(false,"请登录");
    }
}
